package one2many;

import java.util.Date;
import java.util.Iterator;


import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;


import util.HibernateUtil;

public class TestOne2Many {
	//保存Order，同时保存Items
	@Test
	public void save(){
		Session s =HibernateUtil.getSession();
		Transaction t =s.beginTransaction();
		Order order=new Order();
		order.setCreateDate(new Date());
		Item item1=new Item();
		item1.setAmount(10);
		item1.setProductName("anquantao");
		order.getItems().add(item1);
		Item item2=new Item();
		item2.setAmount(5);
		item2.setProductName("gdian");
		order.getItems().add(item2);
		s.save(order);
		t.commit();
	}
	
	@Test//读取Order，同时获取Items
	public void testRead() {
		Session s = HibernateUtil.getSession();
		s.beginTransaction();
		Order order=(Order) s.get(Order.class, 1);
//		Order order=(Order) s.load(Order.class, 1);//get/load效果相同
		System.out.println(order.getCreateDate());
		
		Iterator<Item> items=order.getItems().iterator();
		while (items.hasNext()) {
			Item item = (Item) items.next();
			System.out.println(item.getProductName());
		}
	}
	@Test//修改Item的信息
	public void testUpdateItem(){
		Session s = HibernateUtil.getSession();
		Transaction t =s.beginTransaction();
		Order order=(Order) s.get(Order.class, 1);
//		Order order=(Order) s.load(Order.class, 1);//get/load效果相同
		System.out.println(order.getCreateDate());
		
		Iterator<Item> items=order.getItems().iterator();
		while (items.hasNext()) {
			Item item = (Item) items.next();
			if(item.getId()==1){
				item.setAmount(1);
			}
		}
		t.commit();
	}
	@Test//删除一个Item的信息
	public void testDelete(){
		Session s = HibernateUtil.getSession();
		Transaction t =s.beginTransaction();
		Order order=(Order) s.get(Order.class, 1);
//		Order order=(Order) s.load(Order.class, 1);//get/load效果相同
		System.out.println(order.getCreateDate());
		
		Iterator<Item> items=order.getItems().iterator();
		while (items.hasNext()) {
			Item item = (Item) items.next();
			if(item.getId()==1){
				//cascade="all"
				//item的order_id变为null
				//cascade="all-delete-orphan"
				//item的order_id变为null,并且从数据库中删除
				items.remove();
			}
		}
		t.commit();
	}
	//删除Order及Items
	@Test
	public void testDeleteOrder(){
		Session s = HibernateUtil.getSession();
		Transaction t =s.beginTransaction();
		Order order=(Order) s.get(Order.class, 1);
		s.delete(order);
		t.commit();
	}
}
